import 'dart:async';

import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:library_base/constant/constant.dart';
import 'package:flutter_localizations/flutter_localizations.dart';
import 'package:library_base/global/multi_language.dart';
import 'package:library_base/log/fb_log.dart';
import 'package:library_base/route/app_analysis.dart';
import 'package:library_base/utils/theme_util.dart';
import 'package:library_base/utils/toast_util.dart';
import 'package:get/get.dart';
import 'package:library_base/global/service.dart';
import 'package:library_base/binding/controller_binding.dart';
import 'package:library_base/route/routers.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:library_base/page/2_404_error.dart';
import 'package:library_base/utils/FallbackCupertinoLocalisationsDelegate.dart';
import 'package:module_dispatcher/routers/dispatcher_router.dart';
import 'package:module_common/routers/common_router.dart';

///默认App的启动
class DefaultApp {
  ///运行app
  static Future<void> run() async {
    await initServices();
    Routers.init([
      DispatcherRouter(),
      CommonRouter(),
    ]);

    var app = GetMaterialApp(
      themeMode: ThemeUtil.getThemeMode(),
      theme: ThemeUtil.getTheme(),
      debugShowCheckedModeBanner: !Constant.isReleaseMode,
      getPages: Routers.getPages,
      initialRoute: Routers.splash,
      //Material 风格代理配置
      localizationsDelegates: const [
        GlobalMaterialLocalizations.delegate,
        GlobalWidgetsLocalizations.delegate,
        FallbackCupertinoLocalisationsDelegate(),
      ],
      initialBinding: ControllerBinding(),
      navigatorObservers: [AppAnalysis()],
      //程序支持的语言环境配置
      supportedLocales: const [Locale("zh", "CH")],
      locale: const Locale("zh", "CN"), //设置默认的语言
      fallbackLocale: const Locale("zh", "CN"), //在配置错误的情况下使用的语言
      translations: MultiLanguage(),
      unknownRoute: GetPage(name: Routers.page_404_not_found, page: () => Error404Screen()),
      // onUnknownRoute: (RouteSettings settings){
      //
      // },
      // home: const SplashPage(),
      // onGenerateRoute: FBModuleCenter.generatorByRouteSetting,
      builder: (context, widget) {
        ScreenUtil.init(context, designSize: const Size(750, 1624));
        return MediaQuery(
          //设置文字大小不随系统设置改变
          data: MediaQuery.of(context).copyWith(textScaleFactor: 1.0),
          child: widget!,
        );
      },
    );
    runApp(ToastUtil.init(app));

    ///屏幕刷新率和显示率不一致时的优化，必须挪动到 runApp 之后
    GestureBinding.instance?.resamplingEnabled = true;
  }

  ///初始化服务
  static Future<void> initServices() async {
    await Get.putAsync(() => GlobalConfigService().initApp());
    logger.d('All services started...');
  }
}
